import { LocationState, Path } from 'history'
import React, { Suspense, useEffect } from 'react'
import { Redirect, Switch, useHistory } from 'react-router'
import { Route } from 'react-router-dom'
window.sessionStorage.setItem('__history_pathname', '/')

/**
 * @private
 * @全局路由包装组件
 * @param props beforEach
 * @Message 不阻塞渲染 异步
 */
export const PackingWithAuth: React.FC<{ onChange: PackingOnChangeTypes }> = ({ children, onChange }) => {
  const { push } = useHistory()
  useEffect(() => {
    const from = window.sessionStorage.getItem('__history_pathname') as string
    const to = location.pathname
    if (from === to) return
    window.sessionStorage.setItem('__history_pathname', to)
    onChange(from, to, push)
  }, [location.pathname])

  return (
    <Suspense fallback={<div />}>
      <Switch>
        {children}
        <Route path="*" component={() => <Redirect to="/404" />}></Route>
      </Switch>
    </Suspense>
  )
}

export type PackingOnChangeTypes = (from: string, to: string, next: (path: Path, state?: LocationState) => void) => void
export default PackingWithAuth
